/**
 * Created by yanghenga on 2015/8/11.
 */
// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
define(['ionic'], function () {
    angular.module('starter', ['ionic'])
        .config(configBlock)
        .run(runBlock)
        .constant('serviceName',{
            'list':"UFIDA.U9.ISV.MFGRestDealerSV.Dealer.IGetCustomerGoodsList",
            'type':"UFIDA.U9.ISV.MFGRestDealerSV.Dealer.IGetSaleCategory",
            'credit':"UFIDA.U9.ISV.MFGRestDealerSV.Dealer.IGetCreditBlanceByCustomer",
            'lbs':"UFIDA.U9.ISV.MFGRestDealerSV.Dealer.IGetDistrict",
            'record':"UFIDA.U9.ISV.MFGRestDealerSV.Dealer.ICreateDSO",
            'client':"UFIDA.U9.ISV.MFGRestMultiCallSV.MultiCall.IGetJoinUserInfo",
            'keyword':"UFIDA.U9.ISV.MFGRestDealerSV.Dealer.IQueryItemList",
            'update':"UFIDA.U9.ISV.MFGRestDealerSV.Dealer.IGetGoodsByItemID",
            'addrs':"UFIDA.U9.ISV.MFGRestDealerSV.Dealer.IGetDSOContactAndAddress"
        })
        .factory('storeMessage',['$q','$http','serviceName',function ($q,$http,serviceName,$timeout) {
          //  var search = "",type=false, storeSingle = {},uuid=parent.device?parent.device.uuid:"wewsdere233f";
            var self=this;
            self.paramsObj={
                search:'',
                type:false,
                storeSingle:{},
                uuid:parent.device?parent.device.uuid:"wewsdere233f",
                credit:'',
                userCode:u9.getLoginData(),
                sortList:[]
            }
            var o = {
                getList: function (num) {
                    var defer=$q.defer();
                    u9.showLoading();
                    u9.callSVAlone({
                        name:serviceName.list,
                        params:[self.paramsObj.userCode.UserCode,num.toString(),self.paramsObj.uuid,self.paramsObj.type],
                        onSuccess:function(data){
                            u9.hideLoading();
                            defer.resolve(data);
                        },
                        onFailure:function(err){
                            u9.hideLoading();
                            defer.reject(err);
                        }
                    })

                    return defer.promise;
                },
                getRemoteSearch:function(key){
                    var defer=$q.defer();
                    u9.showLoading();
                    u9.callSVAlone({
                        name:serviceName.keyword,
                        params:[key,self.paramsObj.userCode.UserCode,self.paramsObj.uuid],
                        onSuccess:function(data){
                            u9.hideLoading();
                            defer.resolve(data);
                        },
                        onFailure:function(err){
                            u9.hideLoading();
                            defer.reject(err);
                        }
                    })

                    return defer.promise;
                },
                getSearch:function(){
                    return self.paramsObj.search;
                },
                setSearch: function () {
                    self.paramsObj.search = arguments[0];
                },
                setType:function(bol){
                    self.paramsObj.type=bol;
                },
                getSortList:function(){
                    var defer=$q.defer();
                    if(self.paramsObj.sortList.length>0){
                        $timeout(function(){
                            defer.resolve(self.paramsObj.sortList);
                        })
                    }else{
                        u9.showLoading();
                        u9.callSVAlone({
                            name:serviceName.type,
                            params:[self.paramsObj.userCode.UserCode],
                            onSuccess:function(data){
                                u9.hideLoading();
                                defer.resolve(data);
                            },
                            onFailure:function(err){
                                u9.hideLoading();
                                defer.reject(err);
                            }
                        })
                    }

                    return defer.promise;
                },
                getCredit:function(){
                    if(angular.isNumber(self.paramsObj.credit)){
                        return self.paramsObj.credit;
                    }
                    var defer=$q.defer();
                    u9.showLoading();
                    u9.callSVAlone({
                        name:serviceName.credit,
                        params:[self.paramsObj.userCode.UserCode],
                        onSuccess:function(data){
                            u9.hideLoading();
                            self.paramsObj.credit=data;
                            defer.resolve(data);
                        },
                        onFailure:function(err){
                            u9.hideLoading();
                            defer.reject(err);
                        }
                    })
                    return defer.promise;

                },
                createOrder:function(params){
                    params=angular.extend(params,{'UserCode':self.paramsObj.userCode.UserCode,'OrgCode':self.paramsObj.userCode.OrgCode});
                    var defer=$q.defer();
                    u9.callSVAlone({
                        name:serviceName.record,
                        params:[params],
                        onSuccess:function(data){
                            defer.resolve(data);
                        },
                        onFailure:function(err){
                            defer.reject(err);
                        }
                    });
                    return defer.promise;
                },
                getSingle: function () {
                    return self.paramsObj.storeSingle
                },
                setSingle: function () {
                    self.paramsObj.storeSingle = angular.copy(arguments[0] || {});
                }
            }
            return o;
        }])
        .factory('storeLocalFile',['$q','$http','serviceName',function ($q,$http,serviceName) {
            var self=this;
            var localFile = {
                attent: (localStorage.attent && JSON.parse(localStorage.attent)) || [],
                cart: (localStorage.cart && JSON.parse(localStorage.cart)) || [],
                accounts:(localStorage.accounts && JSON.parse(localStorage.accounts)) || []
            };
            self.updateData=function(arg){
                var defer=$q.defer();
                var ids=[];
                localFile[arg].map(function(v){
                    ids.push(v.ItemID.toString());
                })
                u9.callSVAlone({
                    name:serviceName.update,
                    params:[ids,u9.getLoginData().UserCode],
                    onSuccess:function(data){
                        defer.resolve(data);
                    },
                    onFailure:function(err){
                        defer.reject(err);
                    }
                })
                return defer.promise;
            }
            function storeLocal(arg){
                localStorage[arg]=JSON.stringify(localFile[arg]);
            }
            var pipeFile = {
                delAttent: function (id) {
                    localFile.attent = localFile.attent.filter(function (val, index, arr) {
                        return val.ItemID != id;
                    })
                    storeLocal('attent');
                },
                getData:function(key){
                    
                    return localFile[key];
                },
                isInAttent:function(id){
                    return localFile.attent.filter(function (val, index, arr) {
                        return val.ItemID == id;
                    })
                },
                isInCart:function(id){
                    return localFile.cart.filter(function (val, index, arr) {
                        return val.ItemID == id;
                    })
                },
                insertData:function(key,val){
                    var isexist = false;
                    for (var i = 0; i < localFile[key].length; i++) {
                        if (localFile[key][i].ItemID == arguments[1].ItemID) {
                            localFile[key][i] = arguments[1];
                            isexist = true;
                            break;
                        }
                    }
                    if (!isexist) {
                        localFile[key].unshift(arguments[1]);
                    }
                    storeLocal(key);
                },

                delCart: function (key,id) {
                    localFile[key] = localFile[key].filter(function (val, index, arr) {
                        return val.ItemID != id;
                    });
                    storeLocal(key);
                },
                account:function(){
                    localFile.accounts=arguments[0];
                },
                removePartCart:function(){
                    for(var i=0;i<localFile.accounts.length;i++){
                        for(var j=0;j<localFile.cart.length;j++){
                            if(localFile.cart[j].ItemID==localFile.accounts[i].ItemID){
                                localFile.cart.splice(j,1);
                                break;
                            }
                        }
                    };
                    storeLocal('cart');
                    localFile.accounts=[];
                },
                getAccount:function(){
                    return localFile.accounts;
                },
                getRemoteData:function(){
                    var o=[];
                if(!u9.checkNetwork) return;
                    o.push(self.updateData('attent'),self.updateData('cart'));
                    $q.all(o).then(function(data){
                        localFile.attent=data[0];
                        localFile.cart=data[1];
                        storeLocal('cart');
                        storeLocal('attent');

                    },function(err){
                        u9.alert(err.message||err._message);
                    })
                }
            }
            return pipeFile;

        }] )
        .factory('storeReceive',['$q','$http','serviceName',function($q,$http,serviceName){
            var self=this,r={},localReceive=[];
            function storeLocal(){
                localStorage.receiveInfo=JSON.stringify(localReceive);
            }
            //两个参数 new ,old activeId
            r.setactiveReceive=function(){
                if(arguments[0]){
                    for(var i=0;i<localReceive.length;i++){
                        if(localReceive[i].CustomerSiteID==arguments[0]){
                            localReceive[i].active=true;
                        }else{
                            localReceive[i].active=false;
                        }
                    }
                    //storeLocal();
                    return true;
                }else{
                    return false;
                }
            };
            r.getactiveReceive=function(){
                return localReceive.filter(function(v,i,ary){return v.active})[0];
            };
            r.setReceive=function(){
                u9.callSVAlone({
                    name:serviceName.addrs,
                    params:[u9.getLoginData().UserCode],
                    onSuccess:function(data){
                        localReceive=data;
                    },
                    onFailure:function(err){
                       console.log('获取联系地址失败了')
                    }
                })
            },
            r.getReceive=function(){
                var defer= $q.defer();
                if(localReceive.length>0){
                    defer.resolve(localReceive);
                }else{
                    u9.showLoading();
                    u9.callSVAlone({
                        name:serviceName.addrs,
                        params:[u9.getLoginData().UserCode],
                        onSuccess:function(data){
                            localReceive=data;
                            u9.hideLoading();
                            defer.resolve(data);

                        },
                        onFailure:function(err){
                            u9.hideLoading();
                            defer.reject(err);
                        }
                    })
                }


                return defer.promise;
            }
            return r;
        }])
        .factory('lbs',['$q','$ionicPopup','serviceName',function($q,$ionicPopup,serviceName){

            var l={};
            l.getCountry=function(){
                var defer=$q.defer();
                u9.showLoading();
                u9.callSVAlone({
                    name:serviceName.lbs,
                    params:[0,0],
                    onSuccess:function(data){
                        u9.hideLoading();
                        defer.resolve(data);
                    },
                    onFailure:function(err){
                        u9.hideLoading();
                        defer.reject(err);
                    }
                })
                return defer.promise;

            },
            l.getLbs=function(k,id){
                var defer=$q.defer();
                u9.showLoading();
                u9.callSVAlone({
                    name:serviceName.lbs,
                    params:[k,id],
                    onSuccess:function(data){
                        u9.hideLoading();
                        defer.resolve(data);
                    },
                    onFailure:function(err){
                        u9.hideLoading();
                        defer.reject(err);
                    }
                })
                return defer.promise;

            }
            return l;
        }])
        .controller('homeCtrl', homeCtr)
        .controller('singleCtrl', singleCtrl)
        .controller('searchCtrl', searchCtrl)
        .controller('cartCtrl', cartCtrl)
        .controller('attentCtrl', attentCtrl)
        .controller('accountCtrl', accountCtrl)
        .controller('sortCtrl', sortCtrl)
        .controller('receiveCtr',receiveCtr)
        .controller('addReceiveCtr',addReceiveCtr)
    runBlock.$inject=['$ionicLoading','$ionicPlatform','storeLocalFile','storeReceive']
    configBlock.$inject = ['$stateProvider', '$urlRouterProvider', '$ionicConfigProvider'];
    homeCtr.$inject = ['$scope', '$ionicPopover', '$state', 'storeMessage'];
    singleCtrl.$inject = ['$scope', '$stateParams', 'storeLocalFile', '$ionicLoading','storeLocalFile','$ionicPopup'];
    searchCtrl.$inject = ['$scope','$state','storeMessage','$timeout','$ionicHistory'];
    cartCtrl.$inject = ['$scope', 'storeLocalFile','$ionicLoading','$state','$ionicPopup','storeMessage','$animate'];
    attentCtrl.$inject = ['$scope','storeLocalFile','$state','$animate'];
    accountCtrl.$inject = ['$scope','storeLocalFile','$state','$ionicPopup','storeReceive','storeMessage','$timeout'];
    sortCtrl.$inject = ['$scope', '$state', '$ionicScrollDelegate', 'storeMessage','$timeout','$ionicHistory'];
    receiveCtr.$inject=['$scope','$state','storeReceive','$ionicHistory'];
    addReceiveCtr.$inject=['$scope','$ionicHistory','storeReceive','$http','lbs'];
    function configBlock(routerProvide, urlStateProvide, configProvider) {
        routerProvide.state('home', {
            url: '/home',
            templateUrl: 'view/home.html',
            controller: 'homeCtrl'

        })
            .state('single', {
                url: '/single/:product',
                templateUrl: 'view/single.html',
                controller: 'singleCtrl'
            })
            .state('search', {
                url: '/search',
                templateUrl: 'view/search.html',
                controller: 'searchCtrl'
            })
            .state('cart', {
                url: '/cart',
                templateUrl: 'view/cart.html',
                controller: 'cartCtrl'
            })
            .state('attention', {
                url: '/attention',
                templateUrl: 'view/attent.html',
                controller: 'attentCtrl'
            })
            .state('account', {
                url: '/account',
                templateUrl: 'view/account.html',
                controller: 'accountCtrl'
            })
            .state('sort', {
                url: '/sort',
                templateUrl: 'view/sort.html',
                controller: 'sortCtrl'
            })
            .state('receive', {
                url: '/receive',
                templateUrl: 'view/receive.html',
                controller: 'receiveCtr'
            })
            .state('addReceive', {
                url: '/addReceive',
                templateUrl: 'view/addReceive.html',
                controller: 'addReceiveCtr'
            });
        urlStateProvide.otherwise('/home');
        //configProvider.views.maxCache(0);
        //configProvider.views.forwardCache(true);
        configProvider.platform.android.navBar.alignTitle('center');
        configProvider.platform.android.backButton.previousTitleText(false);
        configProvider.backButton.text("").icon('ion-chevron-left');
    }

    function runBlock($ionicLoading,$ionicPlatform,storeLocalFile,storeReceive) {
        storeLocalFile.getRemoteData();
        storeReceive.setReceive();
    }
    function homeCtr(scope, $ionicPopover, state, storeMessage) {
        var self=this;
        self.num=0;
        scope.infiniteable=false;
        scope.items=[];
        $ionicPopover.fromTemplateUrl('view/pop.html', {
            scope: scope
        }).then(function (popover) {
            scope.popover = popover;
        });
        scope.closePop = function () {
            scope.popover.hide();
        };
        scope.searchText = storeMessage.getSearch();

        scope.items = [];
        function initData(str){
            storeMessage.getList(self.num).then(function(data){
                if(data&&data.GoodsList&&data.GoodsList.length>0){
                    scope.items=scope.items.concat(data.GoodsList);
                }
            },function(err){
                u9.alert(err._message||err.message);
            }).finally(function(){
                eval(str);
            });
        }
        if(scope.searchText){
            storeMessage.getRemoteSearch(scope.searchText).then(function(data){
                scope.items=data;
            },function(err){
                
                u9.alert(err._message||err.message)
            })
        }else{
            initData("");
            storeMessage.setSearch("");
        }

        scope.doRefresh = function () {
            self.num=0;
            scope.items=[];
            initData("scope.$broadcast('scroll.refreshComplete')");

        }
        scope.loadMore = function () {
            self.num++;
            initData("scope.$broadcast('scroll.infiniteScrollComplete')");

        }
        scope.searchStart = function () {
            state.go('search');
        }
        scope.forwardSingle = function (val) {
            state.go('single', {product: JSON.stringify(val)})
        }
    }
    function singleCtrl(scope, stateParams, storeLocalFile, $ionicLoading,storeLocalFile,$ionicPopup) {
        scope.product = JSON.parse(stateParams.product);
        scope.attrs=scope.product.Description.split('#');
        scope.pushInCart = function () {
            storeLocalFile.insertData('cart',scope.product);
            $ionicLoading.show({
                template: '已经加入购物车',
                duration: 1000
            });
            scope.cartConunt=storeLocalFile.getData('cart').length;
        };
        scope.status={
            attent:storeLocalFile.isInAttent(scope.product.ItemID).length>0?true:false,

        }
        scope.status.attentClass=scope.status.attent?'ion-heart':'ion-android-favorite-outline';
        scope.pushInAttent=function($event){
            if(scope.status.attent){
                storeLocalFile.delCart('attent',scope.product.ItemID);
                scope.status.attent=false;
                scope.status.attentClass='ion-android-favorite-outline';
                /*scope.$apply(function(){

                })*/
               /* u9.confirm("一定要取消关注么",'取消关注').then(function(res){
                    if(res){
                        storeLocalFile.delCart('attent',scope.product.ItemID);
                        scope.$apply(function(){
                            scope.status.attent=false;
                            scope.status.attentClass='ion-android-favorite-outline';
                        })

                    }
                })*/
                return
            }else{
                storeLocalFile.insertData('attent',scope.product);
                scope.status.attent=true;
                scope.status.attentClass='ion-heart';
                $ionicLoading.show({
                    template: '已关注',
                    duration: 1000
                });
            }

            /*if(target.tagName=="I"){
                angular.element(target).removeClass('ion-android-favorite-outline').addClass('ion-heart');
                angular.element(target).parent().addClass('assertive');
            }else{
                angular.element($event.target).children("i").removeClass('ion-android-favorite-outline').addClass('ion-heart');
                angular.element($event.target).addClass('assertive');
            }*/

        };
        scope.cartConunt=storeLocalFile.getData('cart').length;
    }
    function searchCtrl(scope,$state,storeMessage,$timeout,$ionicHistory) {
        scope.form={};
        scope.form.searchText='';
        scope.search=function(){
            storeMessage.setSearch(scope.form.searchText);
            $ionicHistory.clearCache();
            $timeout(function(){
                $state.go('home');
            })
            /*if(scope.form.searchText){
                storeMessage.setSearch(scope.form.searchText);
                $ionicHistory.clearCache();
                $timeout(function(){
                    $state.go('home');
                })
            }else{

            }*/
        }
    }
    function cartCtrl(scope, storeLocalFile,$ionicLoading,state,ionicPopup,storeMessage,animate ) {
        var self=this;
        scope.items =storeLocalFile.getData('cart');
        scope.allList={
            selected:false,
            money:0
        };
        scope.filterList=[];
        scope.selectAll=function(){
            scope.items.forEach(function(v,i){
                v.selected=scope.allList.selected;
            });
            scope.countMoney();
        }

        if(angular.isObject(self.pro=storeMessage.getCredit())){
            self.pro.then(function(data){
                scope.credit=data;
            },function(err){
                u9.alert(err._message||err.message);
            })
        }else{
            scope.credit=storeMessage.getCredit();
        }


        scope.changecount = function (v,p) {
            
            p ? v.OrderByQtyPU++ : v.OrderByQtyPU > 1 && v.OrderByQtyPU--;
            v.money = v.OrderByQtyPU * v.Price;
            scope.countMoney();
        }
        scope.filterItems = function () {
            scope.countMoney();
            if(scope.filterList.length==scope.items.length){
                scope.allList.selected=true;
            }else{
                scope.allList.selected=false;
            }

        }
        scope.countMoney=function(val) {

            if(val){
                if(/^\d+$/g.test(val.OrderByQtyPU)){
                    val.money=val.OrderByQtyPU*val.Price;
                }else{
                    $ionicLoading.show({
                        template: '请正确填写数量',
                        duration: 1000
                    })
                    return ;
                }
            }
            scope.allList.money=0;
            utilFilter();


        }
        scope.forwardAccount=function(){
            if(scope.filterList.length>0){
                if(scope.allList.money>0){
                    storeLocalFile.account(scope.filterList);
                    state.go('account');
                }else{
                    u9.alert('商品数量不能为0哦')
                }

            }else{
                u9.alert('还没有选择商品呢')
            }


        }
        function backParent(ele){
            if(ele.hasClass('item')){
                ele.css({'-webkit-transform': 'translate(-120px, 0px)',
                    '-webkit-transition': 'all 0.5s'});
            }else{
                backParent(ele.parent());
            }
        }
        scope.swipeItem=function(event){
            backParent(angular.element(event.target));
        }
        scope.cancelRemove=function(event){
            var ele= angular.element(event.target.parentNode.previousSibling.previousSibling) ;
            ele.css({'-webkit-transform': 'translate(0px, 0px)',
                '-webkit-transition': 'all 0.5s'});

        }
        scope.removeItem=function(v,i,event){
            try{
                storeLocalFile.delCart('cart',v.ItemID);
                scope.items.splice(i,1);
            }catch (err){
                u9.alert(err.message);
            }

        }
        function utilFilter(){
            scope.filterList = scope.items.filter(function (v, i, ary) {
                return v.selected;
            })

            scope.filterList.forEach(function(v,i){
                scope.allList.money+= v.money;
            })
        }
        scope.filterItems();

    }
    function accountCtrl(scope,storeLocalFile,state,$ionicPopup,storeReceive,storeMessage,$timeout) {

        var self=this, date=new Date(),orderList=[];
        scope.orderObj={};
        scope.orderObj.totalMoney=0;
        scope.orderObj.orders=storeLocalFile.getAccount();
        scope.orderObj.receiveInfo=storeReceive.getactiveReceive()||"";
        scope.orderObj.receiveInfo.addrs=scope.orderObj.receiveInfo? scope.orderObj.receiveInfo.CountryName+scope.orderObj.receiveInfo.ProvinceName+scope.orderObj.receiveInfo.CityName+scope.orderObj.receiveInfo.CountyName+isDefined(scope.orderObj.receiveInfo.Address1Name)+isDefined(scope.orderObj.receiveInfo.Address2Name)+isDefined(scope.orderObj.receiveInfo.Address3Name):"";
        scope.orderObj.id=232332;
        scope.orderObj.status="未确认";
        scope.orderObj.orders.forEach(function(v,i,ary){
            orderList.push({
                'ItemID': v.ItemID,
                'OrderByQtyPU': v.OrderByQtyPU,
                'Memo':""
            });
            scope.orderObj.totalMoney+=v.money
        });
        function isDefined(k){
            return k||"";
        }
        scope.orderObj.date=date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
        if(angular.isObject(self.pro=storeMessage.getCredit())){
            self.pro.then(function(data){
                scope.credit=data;
            },function(err){
                u9.alert(err._message||err.message);
            })
        }else{
            scope.credit=storeMessage.getCredit();
        }
        scope.selectDatePicker=function(){
            var datePicker=datePicker||parent.datePicker,
                options={
                    date: date,
                    mode: 'date',
                    okText:'确定',
                    cancelText:'取消',
                    todayText:'今天',
                    doneButtonLabel:'确定',
                    cancelButtonLabel:'取消'
                };
            function successCallback(date){
                scope.$apply(function(){
                    scope.orderObj.date=date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
                })
            }
            function failCallback(error){
                (u9&&u9.alert('error:'+error))||$ionicPopup.alert('error:'+error);
            }
            datePicker.show(options,successCallback,failCallback)
        }
        scope.createOrder=function(){
            var o= {
                'DSOLinelist':orderList,
                'RequireDate':scope.orderObj.date,
                'CustomerSiteID':scope.orderObj.receiveInfo.CustomerSiteID
            }
            u9.showLoading();
            storeMessage.createOrder(o).then(function(data){
                u9.hideLoading();
                if(data){
                    u9.alert("订单提交成功").then(function(res){
                        storeLocalFile.removePartCart();
                        if(res){
                            state.go('home');
                        }
                    });
                }else{
                    u9.alert("让您失望了，提交订单出错了");
                }

            },function(err){
                u9.hideLoading();
                u9.alert(err._message||err.message);
            });
        }
    }
    function attentCtrl(scope, storeLocalFile,state,animate) {
        scope.doRefresh=function(){
            scope.items=storeLocalFile.getData('attent');
            scope.$broadcast('scroll.infiniteScrollComplete');
        }
        scope.items=storeLocalFile.getData('attent');
        scope.forwardSingle = function (val) {
            state.go('single', {product: JSON.stringify(val)})
        }
        function backParent(ele){
            if(ele.hasClass('item')){
                ele.css({'-webkit-transform': 'translate(-120px, 0px)',
                    '-webkit-transition': 'all 0.5s'});
            }else{
                backParent(ele.parent());
            }
        }
        scope.swipeItem=function(event){
            backParent(angular.element(event.target));
        }
        scope.cancelRemove=function(event){
            var ele= angular.element(event.target.parentNode.previousSibling.previousSibling) ;
            ele.css({'-webkit-transform': 'translate(0px, 0px)',
                '-webkit-transition': 'all 0.5s'});

        }
        scope.removeItem=function(v,i,event){
            try{
                storeLocalFile.delCart('attent',v.ItemID);
                scope.items.splice(i,1);
            }catch (err){
                u9.alert(err.message);
            }

        }
    }
    function sortCtrl(scope, state, ionicScrollDelegate, storeMessage,$timeout,$ionicHistory) {
        var self=this;
        scope.currentIndex = 0;
        scope.currentList = [];
        scope.items=[];
        storeMessage.setType(true);
        storeMessage.getSortList().then(function(data){
            if(data){
                scope.items=data;
                scope.currentList=scope.items[scope.currentIndex].SecondInfo;
            }
        },function(err){
            u9.alert(err._message||err.message)
        });
        scope.searchStart = function () {
            state.go('search');
        }


        scope.switchList = function (event, val) {
            angular.element(event.target.parentNode.children).removeClass('active');
            angular.element(event.target).addClass('active');
            scope.currentList = val.SecondInfo;
           /* self.getSortList(val.CateID);*/
            var pos = event.target.offsetTop || 0, itemH = event.target.clientHeight,
                parentH = event.target.parentNode.clientHeight,
                viewH = event.target.parentNode.parentNode.parentNode.parentNode.clientHeight,
                scrollH = ionicScrollDelegate.$getByHandle('small').getScrollPosition().top,
                diff = parentH - scrollH;
            if (diff > viewH) {
                //需要滚动
                if (diff - pos > viewH) {
                    ionicScrollDelegate.$getByHandle('small').scrollBy(0, scrollH + pos, true);
                } else {
                    ionicScrollDelegate.$getByHandle('small').scrollTo(0, (diff - viewH + scrollH), true);
                }
            } else {
                return;
            }


            //ionicScrollDelegate.$getByHandle('small').scrollTo(0,)

        }
       /* self.getSortList=function(id){
            storeMessage.getSortList(id).then(function(data){
                scope.currentList=data;
            },function(err){
                u9.alert(err._message||err.message)
            })
        }*/
       /* storeMessage.getList(0).then(function(data){
            if(data&&data.GoodsList&&data.GoodsList>0){
                scope.items=scope.items.concat(data.GoodsList);
                self.getSortList(data.GoodsList[0].CateID);
            }

        },function(err){
            u9.alert(err._message||err.message)
        })*/


        scope.searchProduct = function (word) {

            storeMessage.setSearch(word);
            $ionicHistory.clearCache();
            $timeout(function(){
                state.go('home');
            })

        }

    }
    function receiveCtr(scope,state,storeReceive,$ionicHistory){
        storeReceive.getReceive().then(function(data){
            scope.addrs=data;
        },function(err){
            u9.alert(err._message||err.message);
        })
        scope.setActive=function(v){
            v.active=true;
            storeReceive.setactiveReceive(v.CustomerSiteID);
            $ionicHistory.goBack();
        }

    }
    function addReceiveCtr(scope,$ionicHistory,storeReceive,http,lbs){
        var o=scope.o={
            addrsShow:false,
            items:[],
            currentStatus:0,
            next:0,
            accept:[],
            receiver:{
                name:'',
                tel:'',
                addrs:""
            }
        }
        scope.selectContacts=function(){
            var contacts=navigator.contacts||paren.navigator.contacts;
            contacts.pickContact(function(contact){
                scope.$apply(function(){
                    o.receiver.name=contact.displayName;
                    o.receiver.tel=Number(contact.phoneNumbers[0]['value']);
                })

            },function(err){
                u9.alert(err._message||err.message)
            });
        }
        scope.saveReceiver=function(){
            o.receiver.id=(new Date()).getTime();
            storeReceive.storeReceive(o.receiver);
            $ionicHistory.goBack();
        }
        scope.lbsBack=function(v) {
            var id;
            o.addrsShow=false;

            switch (v.key) {
                case 0:
                    o.receiver.country = '';
                case 1:
                    o.receiver.province = '';
                case 2:
                    o.receiver.city = '';
                case 3:
                    o.receiver.zone = '';
                    o.accept=o.accept.splice(0,o.accept.indexOf(v));
                    id=o.accept.length>0?o.accept[o.accept.length-1].ID:0;
            }
            scope.getCurrentList(v,id);
        }

        scope.getCurrentList=function(v,type){
            var arg=arguments;
            if(!v||type==0){
                lbs.getCountry().then(function(data){
                    o.items=data;
                    arg.length>0?o.currentStatus++:""

                },function(err){
                    u9.alert(err._message||err.message);
                });
                return;
            }
            if(type){
                o.currentStatus= v.key;
            }else{
                if(o.addrsShow){
                    return;
                }
                switch (o.currentStatus){
                    case 0:o.receiver.country= v.Name;break;
                    case 1:o.receiver.province= v.Name;break;
                    case 2:o.receiver.city= v.Name;break;
                    case 3:o.receiver.zone= v.Name;break;
                }
                o.accept.push({key:o.currentStatus,Name: v.Name,ID: v.ID});
                o.currentStatus+=1;
            }

            var id=type?type: v.ID;
            if(o.currentStatus>=4){
                o.addrsShow=true
                return;
            }
            lbs.getLbs(o.currentStatus,id).then(function(data){
                o.items=data;

            },function(err){
                u9.alert(err._message||err.message);
            })


        }
        scope.getCurrentList();
    }
})


